using UnityEngine;
using System.Collections;

[System.Serializable]
public class OpenDoor : MonoBehaviour {
	
	/**
	 * http://answers.unity3d.com/questions/14361/open-and-close-a-door-with-a-keypress.html
	 * Adapted to C# by André Nilsen
	 * 5. October 2012
	 **/
	
	private bool isDoorOpen = false;
	private GameObject currentDoor;
	
	public AudioClip doorOpenSound;
	public AudioClip doorCloseSound;
	
	
	// Added by André Nilsen
	// 5. October 2012
	public string doorOpenAnim = "dooropen";
	public string doorCloseAnim = "doorclose";
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKey("e")) {
			RaycastHit hit = new RaycastHit();
			
			if (Physics.Raycast (transform.position, transform.forward, out hit, 2f)) {
				Debug.Log(hit.collider.gameObject.name);
				
				if (hit.collider.gameObject.tag == "door" && !isDoorOpen) {
					currentDoor = hit.collider.gameObject;
					
					// Edited by André Nilsen
					// 5. October 2012
					// Changed "dooropen" -> doorOpenAnim
					Door(doorOpenSound, true, doorOpenAnim, currentDoor);
				} else if (isDoorOpen) {
					currentDoor = hit.collider.gameObject;
					
					// Edited by André Nilsen
					// 5. October 2012
					// Changed "doorclose" -> doorCloseAnim
					Door(doorCloseSound, false, doorCloseAnim, currentDoor);
				}
			}
		}
	}
	
	void Door(AudioClip aClip, bool openCheck, string animName, GameObject thisDoor) {
		audio.PlayOneShot(aClip);
		
		isDoorOpen = openCheck;
		
		thisDoor.transform.parent.animation.Play(animName);
	}
}
